package com.zhangzy.qm.action;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.json.JSONArray;
import org.json.JSONObject;

import com.zhangzy.qm.dao.AblumDao;
import com.zhangzy.qm.dao.HistoryDao;
import com.zhangzy.qm.dao.OptionDao;
import com.zhangzy.qm.dao.RankingDao;
import com.zhangzy.qm.dao.TopicDao;
import com.zhangzy.qm.dao.UserTokenDao;
import com.zhangzy.qm.entity.Ablum;
import com.zhangzy.qm.entity.History;
import com.zhangzy.qm.entity.Option;
import com.zhangzy.qm.entity.Ranking;
import com.zhangzy.qm.entity.Topic;
import com.zhangzy.qm.entity.UserToken;
import com.zhangzy.qm.util.Constants;
import com.zhangzy.qm.util.FileUtil;
import com.zhangzy.qm.util.HttpUtil;
/**
 * 接口操作类
 * @Class Name InterfaceController
 * @Author zhenyu
 * @Create In May 5, 2012
 */
public class InterfaceController {
	private HttpServletRequest request = ServletActionContext.getRequest();
	private HttpServletResponse response = ServletActionContext.getResponse();
	private static final Logger logger = Logger.getLogger("ulog");
	private File userImage;	
	private String userName;
	private int subjectId;
	private int score;
	private int aoscaNumber;
	private String userId;
	private RankingDao rankingDao;//排行榜dao
	private TopicDao topicDao;//试题dao
	private OptionDao optionDao;//选项dao
	private AblumDao ablumDao;//专辑dao
	private HistoryDao historyDao;//下载历史dao
	private UserTokenDao userTokenDao;
	private String serverAddress =Constants.serverPath+request.getContextPath()+"/imageDisplay.action?imageUrl="; 
	
	public RankingDao getRankingDao() {
		return rankingDao;
	}
	public void setRankingDao(RankingDao rankingDao) {
		this.rankingDao = rankingDao;
	}
	public File getUserImage() {
		return userImage;
	}
	public void setUserImage(File userImage) {
		this.userImage = userImage;
	}
	public TopicDao getTopicDao() {
		return topicDao;
	}
	public void setTopicDao(TopicDao topicDao) {
		this.topicDao = topicDao;
	}
	public OptionDao getOptionDao() {
		return optionDao;
	}
	public void setOptionDao(OptionDao optionDao) {
		this.optionDao = optionDao;
	}
	public AblumDao getAblumDao() {
		return ablumDao;
	}
	public void setAblumDao(AblumDao ablumDao) {
		this.ablumDao = ablumDao;
	}
	
	
	public void topRelease(){
	try {
		long now = new Date().getTime();
		//String userId = HttpUtil.getString(request, "userId","");
		//String userName = HttpUtil.getString(request, "userName","");
		//int subjectId = HttpUtil.getInt(request, "subjectId",0);
		//int score = HttpUtil.getInt(request, "score",0);
		//int aoscaNumber = HttpUtil.getInt(request, "aoscaNumber",0);
		logger.info("userId:"+userId+",userName:"+userName+",subjectId:"+subjectId+",score:"+score+",aoscaNumber"+aoscaNumber);
		boolean flag = ablumDao.isExist("select count(*) from Ablum a where a.id="+subjectId);
		StringBuilder sb = new StringBuilder();
		if(flag){
			Ablum ablum = new Ablum();
			ablum.setId(subjectId);
			Ranking ranking = new Ranking();
			ranking.setUserId(userId);
			ranking.setScore(score);
			ranking.setAblum(ablum);
			ranking.setUserName(userName);
			ranking.setAoscaNumber(aoscaNumber);
			if(userImage!=null){			
				userImage.renameTo(new File(Constants.uploadPath+now+".png")); //文件上传后重命名
				ranking.setUserImage(Constants.uploadPath+now+".png");
			}
			ranking.setSaveTime(new Date());
			Ranking obj = (Ranking) rankingDao.save(ranking);
			if(obj.getId()!=0){
				sb.append("{\"errorCode\":\"0\",\"errorMessage\":\"\"}");
			}else{
				sb.append("{\"errorCode\":\"1025\",\"errorMessage\":\"用户不存在\"}");
			}
		}else{
			sb.append("{\"errorCode\":\"1026\",\"errorMessage\":\"专辑不存在\"}");
		}
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out;
		out = response.getWriter();
		out.println(sb.toString());
		out.flush();
		out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}	
	
	public void topList()throws Exception{
		try {
		StringBuilder hql = new StringBuilder();
		StringBuilder sb = new StringBuilder("{\"topList\":[");
		hql.append("from Ranking r group by r.ablum.id ");
		//hql.append("from Ablum a where a.state=2");
		List<Ranking> dataList = rankingDao.query(hql.toString());
		//List<Ablum> dataList = ablumDao.query(hql.toString());
		int i = 0;
		for(Ranking r :dataList){
			String hql2="from Ranking r where r.ablum.id="+r.getAblum().getId()+" order by r.score desc ";
			List<Ranking> rankingList = rankingDao.query(hql2,0,100);
			if(rankingList==null || rankingList.size()<=0){
				continue;
			}
			if(i!=0){
				sb.append(",");
			}
			sb.append("{");
			sb.append("\"subjectId\":\""+r.getAblum().getId()+"\" , ");
			sb.append("\"subjectName\":\""+r.getAblum().getTitle()+"\" , ");
			sb.append("\"subjectImageURL\":\""+Constants.serverPath+r.getAblum().getImageUrl().replace("D://resin-pro-3.1.8/webapps", "")+"\" , ");
			sb.append("\"userList\":[");
			int j = 0;
			for(Ranking r1:rankingList){
				if(j!=0){
					sb.append(",");
				}
				String userImg = "";
				if(r1.getUserImage()!=null && !"".equals(r1.getUserImage())){
					userImg = Constants.serverPath+r1.getUserImage().replace("D://resin-pro-3.1.8/webapps", "");
				}
				sb.append("{");
				sb.append("\"userId\":\""+r1.getUserId()+"\" , ");
				sb.append("\"userName\":\""+r1.getUserName()+"\" , ");
				sb.append("\"userImage\":\""+userImg+"\" , ");
				sb.append("\"score\":\""+r1.getScore()+"\" , ");
				sb.append("\"aoscaNumber\":\""+r1.getAoscaNumber()+"\"");
				sb.append("}");
				j++;
			}
			sb.append("]");
			sb.append("}");
			i++;
		}
		sb.append("]}");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out;		
			out = response.getWriter();
			out.println(sb.toString());
			out.flush();
			out.close();
		}catch(Exception e){
			logger.error("topList",e);
		}
	}
	
	public void subjectList(){
		try {
		String userId = HttpUtil.getString(request, "userId","");
		String hql ="from Ablum a where a.state=2";		
		String hql2 ="from History his where his.userId='"+userId+"' and his.ablum.id=";		
		List<Ablum> dataList = ablumDao.query(hql.toString());
		StringBuilder sb = new StringBuilder("{\"subjectList\":[");
		int i = 0;
		boolean isFree = true;
		for(Ablum ab :dataList){
			if(i!=0){
				sb.append(",");
			}
			if(ab.getIsFree()==1){
				isFree=true;
			}else{//如果不是免费的，查询下载历史表是否下载过，下载过则免费
				isFree= historyDao.isExist(hql2+ab.getId());
			}			
			sb.append("{");
			sb.append("\"subjectId\":\""+ab.getId()+"\" , ");
			sb.append("\"subjectName\":\""+ab.getTitle()+"\" , ");
			sb.append("\"subjectImageURL\":\""+Constants.serverPath+ab.getImageUrl().replace("D://resin-pro-3.1.8/webapps", "")+"\" , ");
			sb.append("\"subjectInfo\":\""+ab.getRemark()+"\" , ");
			sb.append("\"IAPID\":\""+ab.getIapid()+"\", ");
			sb.append("\"createTime\":\""+ab.getSaveTime()+"\" , ");
			sb.append("\"isFree\":\""+(isFree==true?0:1)+"\" , ");
			sb.append("\"amount\":\""+ab.getValue()+"\"  ");
			sb.append("}");
			i++;
		}
		sb.append("]");
		sb.append("}");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out;		
			out = response.getWriter();
			out.println(sb.toString());
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
//	public void downLoadSubject(){
//		try {
//		String userId = HttpUtil.getString(request, "userId","");
//		int subjectId = HttpUtil.getInt(request, "subjectId",0);
//		List<Topic> topicList = new ArrayList<Topic> ();
//		String zipPath=Constants.zipPath+userId+"/"+subjectId+"/"+subjectId+"/";//需要打包的专辑资源存放位置
//		String zipSrcPath=zipPath+"/src/";//需要打包的专辑资源存放位置
//		File f1 = new File(zipPath);
//		if(!(f1.exists())){
//			f1.mkdirs();
//		}
//		File f2 = new File(zipSrcPath);
//		if(!(f2.exists())){
//			f2.mkdirs();
//		}	
//		String hql3="from History his where his.userId='"+userId+"' and his.ablum.id="+subjectId;
//		boolean flag=historyDao.isExist(hql3);
//		if(!flag){//不存在，则保存
//			History his = new History();
//			Ablum ablum =new Ablum();
//			ablum.setId(subjectId);
//			his.setUserId(userId);
//			his.setAblum(ablum);
//			historyDao.save(his);//保存			
//		}		
//		if(subjectId!=0){
//			Ablum ab = ablumDao.getAblum(subjectId);	
//			String image="";
//			if(ab.getImageUrl()!=null && !"".equals(ab.getImageUrl())){
//				String urlValue = ab.getImageUrl();
//				//初始化的图片的在特殊的文件里，要把路径替换掉
//				if(urlValue.contains(Constants.uploadPath+"10001/") || urlValue.contains(Constants.uploadPath+"10002/") 
//					|| urlValue.contains(Constants.uploadPath+"10003/") ||urlValue.contains(Constants.uploadPath+"10004/")
//					|| urlValue.contains(Constants.uploadPath+"10005/") || urlValue.contains(Constants.uploadPath+"10006/")){
//					urlValue = urlValue.replaceAll("10001/", "");
//					urlValue = urlValue.replaceAll("10002/", "");
//					urlValue = urlValue.replaceAll("10003/", "");
//					urlValue = urlValue.replaceAll("10004/", "");
//					urlValue = urlValue.replaceAll("10005/", "");
//					urlValue = urlValue.replaceAll("10006/", "");
//				}
//				image = urlValue.replace(Constants.uploadPath, "src/");
//				
//				
//				FileUtil.copy(ab.getImageUrl() , zipPath+image);//复制专辑封面
//			}
//			StringBuilder sb = new StringBuilder("{");
//			sb.append("\"subjectId\":\""+ab.getId()+"\" , ");
//			sb.append("\"subjectName\":\""+ab.getTitle()+"\" , ");
//			sb.append("\"subjectType\":\"0"+ab.getType()+"\" , ");
//			sb.append("\"subjectImage\":\""+image+"\" , ");
//			sb.append("\"subjectInfo\":\""+ab.getRemark()+"\" , ");
//			sb.append("\"paperList\":[");
//			
//			topicList = topicDao.query(" from Topic t where t.ablum.id="+ab.getId());
//			Collections.shuffle(topicList); //打乱顺序
//			int j =0;
//			for(Topic topic:topicList){
//				String qContent ="";
//				if(topic.getType()==1){
//					qContent=topic.getTitle();
//				}else{
//					qContent=topic.getResourceUrl();
//					//初始化的图片的在特殊的文件里，要把路径替换掉
//					if(qContent.contains(Constants.uploadPath+"10001/") || qContent.contains(Constants.uploadPath+"10002/") 
//						|| qContent.contains(Constants.uploadPath+"10003/") ||qContent.contains(Constants.uploadPath+"10004/")
//						|| qContent.contains(Constants.uploadPath+"10005/") || qContent.contains(Constants.uploadPath+"10006/")){
//						qContent = qContent.replaceAll("10001/", "");
//						qContent = qContent.replaceAll("10002/", "");
//						qContent = qContent.replaceAll("10003/", "");
//						qContent = qContent.replaceAll("10004/", "");
//						qContent = qContent.replaceAll("10005/", "");
//						qContent = qContent.replaceAll("10006/", "");
//					}
//					qContent = qContent.replace(Constants.uploadPath,"src/");
//					FileUtil.copy(topic.getResourceUrl() , zipPath+qContent);//复制资源文件 
//				}
//				String subjectInfo = topic.getRemark();
////				if(topic.getRemark()!=null && !"".equals(topic.getRemark())){
////					subjectInfo=topic.getRemark();
////				}else{
////					subjectInfo = topic.getAblum().getRemark();
////				}
//				if(j!=0){
//					sb.append(" , ");
//				}
//				sb.append("{");
//				sb.append("\"questionId\":\""+topic.getId()+"\" , ");
//				sb.append("\"questionType\":\"0"+topic.getType()+"\" , ");
//				sb.append("\"subjectId\":\""+topic.getAblum().getId()+"\" , ");
//				sb.append("\"questionContent\":\""+qContent+"\" , ");
//				sb.append("\"subjectInfo\":\""+subjectInfo+"\" , ");
//				sb.append("\"grade\":\""+topic.getGradeId()+"\" , ");	
//				List<Option> optionList = optionDao.query("from Option o where o.topic.id="+topic.getId());
//				List<Option> resultList = new ArrayList<Option>();
//				if(optionList!=null && (optionList.size()==2 || optionList.size()>=4)){//只有满足此条件才打包
//					for(Option option:optionList){
//						if(option.getRightFlag()==1){
//							resultList.add(option);
//							optionList.remove(option);//此处删除是为了下面的逻辑随机取值时都取的为不正确的结果
//							break;
//						}
//					}
//					Collections.shuffle(optionList); //打乱顺序
//					if(optionList.size()>0){
//						resultList.add(optionList.get(0));
//					}
//					if(optionList.size()>1){
//						resultList.add(optionList.get(1));
//					}
//					if(optionList.size()>2){
//						resultList.add(optionList.get(2));
//					}			
//					if(resultList.size()==1){
//						Option o1 = new Option();
//						o1.setTitle("");
//						Option o2 = new Option();
//						o2.setTitle("");
//						Option o3 = new Option();
//						o3.setTitle("");
//						resultList.add(o1);
//						resultList.add(o2);
//						resultList.add(o3);
//					}else if(resultList.size()==3){
//						Option o1 = new Option();
//						o1.setTitle("");
//						resultList.add(o1);
//					}else if(resultList.size()==0){
//						Option o1 = new Option();
//						o1.setTitle("");
//						Option o2 = new Option();
//						o2.setTitle("");
//						Option o3 = new Option();
//						o3.setTitle("");
//						Option o4 = new Option();
//						o4.setTitle("");
//						resultList.add(o1);
//						resultList.add(o2);
//						resultList.add(o3);
//						resultList.add(o4);
//					}
//					Collections.shuffle(resultList); //打乱顺序 
//				}
//				int i = 0;
//				boolean tempFlag = false;
//				for(Option option:resultList){
//					String optionFlag = "option";
//					if(i==0){
//						optionFlag="A";
//					}else if(i==1){
//						optionFlag="B";
//					}else if(i==2){
//						optionFlag="C";
//					}else if(i==3){
//						optionFlag="D";
//					}
//					if(option.getRightFlag()==1){
//						tempFlag=true;
//						sb.append("\"option"+optionFlag+"\":\""+option.getTitle()+"\" , ");	
//						sb.append("\"correctAnswer\":\""+optionFlag+"\" ");						
//					}else{
//						sb.append("\"option"+optionFlag+"\":\""+option.getTitle()+"\" ");				
//					}
//					if(i!=resultList.size()-1){
//						sb.append(",");
//					}					
//					i++;
//				}
//				if(!tempFlag){//没有正确答案，默认A
//					sb.append(",\"correctAnswer\":\"A\" ");		
//				}
//				if(resultList.size()==2){//只有两个选项，c,d 设置为空
//					sb.append(",\"optionC\":\"\",\"optionD\":\"\"");	
//				}				
//				j++;
//				sb.append("}");
//		}
//		sb.append("]");
//		sb.append("}");	  
//		FileUtil.writeFile(sb.toString(),zipPath+subjectId+".txt");//写json文件	
//		//System.out.println("zipPaht:"+zipPath);
//		ZipUtil.zip(Constants.zipPath+userId+"/"+subjectId, Constants.zipPath+userId+"/"+subjectId+".zip");
//		//FileUtil.downLoad(subjectId+"",Constants.zipPath,response);//文件下载
//		JSONObject json = new JSONObject();
//		json.put("url", Constants.serverPath+request.getContextPath()+"/zips/"+userId+"/"+subjectId+".zip");
//		response.setContentType("text/html");
//		response.setCharacterEncoding("UTF-8");
//		PrintWriter out;		
//		try{
//			out = response.getWriter();
//			out.println(json.toString());
//			out.flush();
//			out.close();
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//	 }
//	}catch(Exception e){
//		e.printStackTrace();
//	}
//	}
	public void downLoadSubject(){
		try {
			String userId = HttpUtil.getString(request, "userId","");
			int subjectId = HttpUtil.getInt(request, "subjectId",0);
			String hql3="from History his where his.userId='"+userId+"' and his.ablum.id="+subjectId;
			boolean flag=historyDao.isExist(hql3);
			if(!flag){//不存在，则保存
				History his = new History();
				Ablum ablum =new Ablum();
				ablum.setId(subjectId);
				his.setUserId(userId);
				his.setAblum(ablum);
				historyDao.save(his);//保存			
			}				
			JSONObject json = new JSONObject();
			json.put("url", Constants.serverPath+request.getContextPath()+"/zips/"+subjectId+".zip");
			response.setContentType("text/html");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out;		
			try{
				out = response.getWriter();
				out.println(json.toString());
				out.flush();
				out.close();
			}catch(Exception e){
				logger.error(e.getStackTrace());
			}
			}catch(Exception e){
				logger.error(e.getStackTrace());
		}
	}
	
	/**
	 * 使用zipFile 初始化数据库
	 * @throws Exception 
	 * @Methods Name initDataByFile
	 * @Create In Jun 24, 2012 By zhenyu void
	 */
	public  void initDataByFile() {
		ArrayList<String> fileList = new ArrayList<String>();
		try {
			FileUtil.readFileName(Constants.initFilePath,fileList);
			for(String file :fileList){
				System.out.println("read file:"+file+" start");
				doInit(file);
				System.out.println("read file:"+file+" end");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private  void  doInit(String file) throws Exception{
		String strJson = FileUtil.readFile(file);
		JSONObject json = new JSONObject(strJson);
		String subjectId = (String)json.get("subjectId");
		String subjectName = (String)json.get("subjectName");
		String subjectType = (String)json.get("subjectType");
		String subjectImage = (String)json.get("subjectImage");
		String subjectInfo = (String)json.get("subjectInfo");
		JSONArray paperList = (JSONArray)json.get("paperList");
		Ablum ablum = new Ablum();
		ablum.setTitle(subjectName);
		ablum.setType(Integer.valueOf(subjectType));
		ablum.setImageUrl(subjectImage.replace("src/", Constants.uploadPath+subjectId+"/"));
		ablum.setRemark(subjectInfo);
		ablum.setIsFree(1);
		ablum.setState(2);
		ablum.setSaveTime(new Date());
		ablumDao.save(ablum);//保存专辑
		if(paperList!=null && paperList.length()>0){
			for(int i =0; i<paperList.length(); i++){
				JSONObject tmp = (JSONObject) paperList.get(i);
				int questionType = tmp.getInt("questionType");
				String questionContent = tmp.getString("questionContent");
				String remark = tmp.getString("subjectInfo");
				int grade = tmp.getInt("grade");
				String optionA = tmp.getString("optionA");
				String optionB = tmp.getString("optionB");
				String optionC = tmp.getString("optionC");
				String optionD = tmp.getString("optionD");
				String correctAnswer = tmp.getString("correctAnswer");
				Topic t = new Topic();
				t.setAblum(ablum);
				if(questionType==1){
					t.setTitle(questionContent);
				}else{
					t.setResourceUrl(questionContent.replace("src/", Constants.uploadPath+subjectId+"/"));
				}
				t.setType(questionType);
				t.setRemark(remark);
				t.setGradeId(grade);
				t.setSaveTime(new Date());
				topicDao.save(t);//保存试题
				if(optionA!=null && !"".equals(optionA)){
					Option o = new Option();
					o.setTopic(t);
					o.setTitle(optionA);
					int rightFlag = 1;
					if(correctAnswer != null && !"".equals(correctAnswer) && ("option"+correctAnswer).equals("optionA")){
						rightFlag =1;
					}else{
						rightFlag =2;
					}
					o.setRightFlag(rightFlag);
					o.setSaveTime(new Date());
					optionDao.save(o);
				}
				if(optionB!=null && !"".equals(optionB)){
					Option o = new Option();
					o.setTopic(t);
					o.setTitle(optionB);
					int rightFlag = 1;
					if(correctAnswer != null && !"".equals(correctAnswer) && ("option"+correctAnswer).equals("optionB")){
						rightFlag =1;
					}else{
						rightFlag =2;
					}
					o.setRightFlag(rightFlag);
					o.setSaveTime(new Date());
					optionDao.save(o);
				}
				if(optionC!=null && !"".equals(optionC)){
					Option o = new Option();
					o.setTopic(t);
					o.setTitle(optionC);
					int rightFlag = 1;
					if(correctAnswer != null && !"".equals(correctAnswer) && ("option"+correctAnswer).equals("optionC")){
						rightFlag =1;
					}else{
						rightFlag =2;
					}
					o.setRightFlag(rightFlag);
					o.setSaveTime(new Date());
					optionDao.save(o);
				}
				if(optionD!=null && !"".equals(optionD)){
					Option o = new Option();
					o.setTopic(t);
					o.setTitle(optionD);
					int rightFlag = 1;
					if(correctAnswer != null && !"".equals(correctAnswer) && ("option"+correctAnswer).equals("optionD")){
						rightFlag =1;
					}else{
						rightFlag =2;
					}
					o.setRightFlag(rightFlag);
					o.setSaveTime(new Date());
					optionDao.save(o);
				}
				
			}
		}
	}
	public HistoryDao getHistoryDao() {
		return historyDao;
	}
	public void setHistoryDao(HistoryDao historyDao) {
		this.historyDao = historyDao;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public int getSubjectId() {
		return subjectId;
	}
	public void setSubjectId(int subjectId) {
		this.subjectId = subjectId;
	}
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
	public int getAoscaNumber() {
		return aoscaNumber;
	}
	public void setAoscaNumber(int aoscaNumber) {
		this.aoscaNumber = aoscaNumber;
	}
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	
	public static void main(String[] args) throws Exception{
		//initDataByFile();
	}
	
	/**接口编号：	MS0005				
	 *接口名称：	apns注册				
	 *接口说明：	后台需要维护userId和token之间的关系。一个userId只对应一个token，如果上送多次请求，新的token覆盖掉旧的				
	 * @Methods Name retistAPNs
	 * @Create In Sep 15, 2012 By zhenyu void
	 */
	public void retistAPNs(){
		try {
			String userId = HttpUtil.getString(request, "userId","");
			String strToken = HttpUtil.getString(request, "token","");//令牌
			String errorCode = "0";//错误代码
			String errorMessage = "";
			if(!"".equals(userId) && !"".equals(strToken)){//无参数
				String hql="from UserToken t where t.userId='"+userId+"'";
				UserToken userToken=userTokenDao.getTokenByUserId(hql);
				if(userToken==null || userToken.getId()<=0){//不存在，则保存
					UserToken token = new UserToken();
					token.setUserId(userId);
					token.setUserToken(strToken);
					userTokenDao.save(token);//保存			
				}else{
					userToken.setUserToken(strToken);
					userTokenDao.update(userToken);
				}		
			}else{
				errorCode="1025";
				errorMessage="交易失败";
			}
			JSONObject json = new JSONObject();
			json.put("errorCode", errorCode);
			json.put("errorMessage", errorMessage);
			response.setContentType("text/html");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out;		
			try{
				out = response.getWriter();
				out.println(json.toString());
				out.flush();
				out.close();
			}catch(Exception e){
				logger.error("retistAPNs",e);
			}
			}catch(Exception e){
				logger.error("retistAPNs",e);
		}
	}
	public UserTokenDao getUserTokenDao() {
		return userTokenDao;
	}
	public void setUserTokenDao(UserTokenDao userTokenDao) {
		this.userTokenDao = userTokenDao;
	}
}
